const Controller = require("egg").Controller;

class RoleController extends Controller {
  // 获取用户列表
  async getRoleList() {
    try {
      const roleList = await this.ctx.service.role.getRoleList();
      this.ctx.body = {
        code: 200,
        data: roleList,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  //修改角色
  async modifyRole() {
    const { ctx } = this;

    try {
      const { id, name, } = ctx.request.body;
      const { id: user_id } = ctx.decode;
      let params = {
        id,
        name
      };
      if (id) {
        params.editor = user_id;
      } else {
        params.creator = user_id;
      }

      const result = await this.ctx.service.role.modifyRole(params);
      this.ctx.body = {
        code: 200,
        data: result,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  //删除角色
  async deleteRole() {
    const { ctx } = this;
    try {
      const { id } = ctx.request.body;
      const role = await this.ctx.service.role.deleteRole(id);

      this.ctx.body = {
        code: 200,
        data: role,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }


  async findRoleSelfPermissions() {
    const { ctx } = this;
    const { roleId  } = ctx.query;
    try {
      const rolePermissions = await this.ctx.service.role.findRoleSelfPermissions(roleId);
      ctx.body = {
        code: 200,
        data: rolePermissions.map((rolePermission) => {
          return rolePermission.permissionId;
        }),
      };
    } catch (error) {
      ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  async roleAddPermission() {
    const { ctx } = this;
    const { roleId, permissionIds } = ctx.request.body;

    try {
      const rolePermission = await ctx.service.role.roleAddPermission(roleId, permissionIds);
      this.ctx.body = {
        code: 200,
        data: rolePermission,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

}

module.exports = RoleController;
